package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author by jojo
 * @Date 2022/2/26
 * @Description
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1.校验参数
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //校验分页参数
        dto.checkParam();
        //2.条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        if (dto.getStatus()!=null) {
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> iPage = this.page(page, wrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),
                iPage.getTotal(),iPage.getRecords());
    }

//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.参数校验
        if (dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户ID不存在");
        }
        //2.查询当前认证用户是否在 APP端有当前用户，判断该表有没有数据
        ApUserRealname apUserRealname = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
        if (apUserRealname==null) {
            log.error("待审核 实名认证信息不存在  userRealnameId:{}", dto.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该审核表单没有该数据");
        }
        //3.判断认证用户的状态码是否是1
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            log.error("实名认证信息非待审核状态   userRealnameStatus:{}", apUserRealname.getStatus());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"状态码异常");
        }
        //4.实名认证信息 关联 app的用户
        LambdaQueryWrapper<ApUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ApUser::getId,apUserRealname.getUserId());
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if (apUser==null) {
            log.error("实名认证信息 关联 app的用户不存在    userRealnameId:{}, userId:{} ", dto.getId(), apUserRealname.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的app用户不存在");
        }
        //5.修改审核状态
        apUserRealname.setStatus(status);
        //5.1判断驳回的信息
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);
        //5.2判断修改状态是否为9
        if (!AdminConstants.PASS_AUTH.equals(status)) {
            //不为9直接返回
            return ResponseResult.okResult();
        }
        //开通自媒体账户
        WmUser wmUser= createWmUser(apUser);
        //创建作者信息表
        createAuthor(apUser,wmUser);

        if (dto.getId()==5){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"id=5报错");
        }

        return ResponseResult.okResult();
    }

    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        //远程调用ArticleFeign，按id查
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(apUser.getId());
        if (!apAuthorResult.checkCode()) {
            log.error("远程调用ArticleFeign出错：{}",apAuthorResult.checkCode());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor!=null) {
            log.error("作者信息已经存在： {}",apAuthor);
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }
        apAuthor= new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult result = articleFeign.save(apAuthor);
        if (!result.checkCode()) {
            log.error("远程调用ArticleFeign出错：{}",apAuthorResult.checkCode());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }
    /**
     * 开通自媒体用户信息
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //远程查询WemediaFeign 按name查询是否有数据
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if (!wmUserResult.checkCode()) {
            log.error("远程调用WemediaFeign出错：{}",wmUserResult.checkCode());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //判断该用户是否存在，存在抛出异常
        WmUser wmUser = wmUserResult.getData();
        if (wmUser!=null) {
            log.error("自媒体用户已经存在： {}",wmUser);
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户已经存在");
        }
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.USER_STATUS_ALLOW);
        wmUser.setType(AdminConstants.AUTHOR_TYPE);
        wmUser.setCreatedTime(new Date());
        //远程调用
        ResponseResult<WmUser> result = wemediaFeign.save(wmUser);
        if (!result.checkCode()) {
            log.error("远程调用WemediaFeign出错：{}",wmUserResult.checkCode());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return result.getData();
    }
}
